//
//	 ______    ______    ______    
//	/\  __ \  /\  ___\  /\  ___\   
//	\ \  __<  \ \  __\_ \ \  __\_ 
//	 \ \_____\ \ \_____\ \ \_____\ 
//	  \/_____/  \/_____/  \/_____/ 
//
//	Powered by BeeFramework
//
//
//  ECircleBoard.m
//  iHeima
//
//  Created by he chao on 5/27/14.
//  Copyright (c) 2014 leon. All rights reserved.
//

#import "ECircleBoard.h"
#import "FriendCell.h"
#import "AddFriendBoard.h"
#import "UserDetailBoard.h"
#import "AcceptNewFriendBoard.h"

#pragma mark -

@interface ECircleBoard()<UIAlertViewDelegate>
{
	//<#@private var#>
    
    BOOL _haveNoFriends;
    
}
@end

@implementation ECircleBoard

- (void)load
{
    arrayUser = [[NSMutableArray alloc] init];
    [self observeNotification:@"newMessage"];
}

- (void)unload
{
}

#pragma mark - Signal

ON_CREATE_VIEWS( signal )
{
    self.title = @"黑马商圈";
    [self showNaviBar];
    self.navigationController.navigationBarHidden = NO;
    [self showBarButton:BeeUINavigationBar.RIGHT image:IMAGESTRING(@"navi_add")];
    [self loadContent];
    
    [self getFriendList];
}

ON_DELETE_VIEWS( signal )
{
}

ON_LAYOUT_VIEWS( signal )
{
}

ON_WILL_APPEAR( signal )
{
}

ON_DID_APPEAR( signal )
{
}

ON_WILL_DISAPPEAR( signal )
{
}

ON_DID_DISAPPEAR( signal )
{
}

ON_SIGNAL3( BeeUINavigationBar, LEFT_TOUCHED, signal )
{
}

ON_SIGNAL3( BeeUINavigationBar, RIGHT_TOUCHED, signal )
{
    AddFriendBoard *board = [[AddFriendBoard alloc] init];
    [[MainBoard sharedInstance].stack pushBoard:board animated:YES];
}

ON_NOTIFICATION(notification){
    if ([notification is:@"newMessage"]) {
        [self checkUnreadMessage];
    }
}

- (void)checkUnreadMessage{
    NSMutableArray *arrayUnread = [[[NSUserDefaults standardUserDefaults] valueForKey:@"unread"] mutableCopy];
    NSString *strUid = kUserInfo[@"uid"];
    for (int i = 0; i < arrayUser.count; i++) {
        NSMutableArray *array = arrayUser[i];
        for (int k = 0 ; k < array.count; k++) {
            NSMutableDictionary *dictUser = array[k];
            
            for (int j = 0; j < arrayUnread.count; j++) {
                NSMutableDictionary *dict = arrayUnread[j];
                if ([strUid intValue]==[dict[@"uid"] intValue] && [dictUser[@"uid"] intValue]==[dict[@"rid"] intValue]) {
                    [dictUser setObject:dict[@"count"] forKey:@"count"];
                }
            }
        }
        
        
    }
    
    [myTableView reloadData];
}

- (void)loadContent{
    myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.viewWidth, self.viewHeight-50-(IOS7_OR_LATER?64:0))];
    myTableView.delegate = self;
    myTableView.dataSource = self;
    myTableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:myTableView];
    
   
    
    
    UIView* newFriendView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 100)];
    newFriendView.backgroundColor = [UIColor whiteColor];
//    UITapGestureRecognizer* tap  =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(newFriends)];
//    [newFriendView addGestureRecognizer:tap];
    
    
    UIView* selectView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 38)];
    selectView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [newFriendView addSubview:selectView];
    UITapGestureRecognizer* tapFind = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(quickFind)];
    [newFriendView addGestureRecognizer:tapFind];
    
    
    
   // description = [BaseLabel initLabel:@"快速筛选" font:FONT(14) color:RGB(145,145,145) textAlignment:NSTextAlignmentLeft];
    
    CGFloat top = 25; // 顶端盖高度
    CGFloat bottom = 25 ; // 底端盖高度
    CGFloat left = 10; // 左端盖宽度
    CGFloat right = 10; // 右端盖宽度
    UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);
    // 伸缩后重新赋
    
    
    UIImage* image = [UIImage imageNamed:@"search_bg.png"];
    UIImage* bgImage = [image resizableImageWithCapInsets:insets];
    
    UIImageView* bgIv = [[UIImageView alloc]initWithFrame:CGRectMake(25, 7, 270, 25)];
    bgIv.image = bgImage;
    bgIv.layer.cornerRadius = 5;
    bgIv.layer.masksToBounds = YES;
    [selectView addSubview:bgIv];
    
    UILabel* label= [[UILabel alloc]initWithFrame:CGRectMake(140, 10, 100, 20)];
    label.font = [UIFont systemFontOfSize:13];
    label.textColor = [UIColor grayColor];
    label.text = @"快速筛选";
    [selectView addSubview:label];
    selectView.userInteractionEnabled = NO;
    
    UIImageView* quickSel = [[UIImageView alloc]initWithFrame:CGRectMake(label.frame.origin.x-20, label.frame.origin.y+2, 15, 15)];
    quickSel.image = [UIImage imageNamed:@"search@2x.png"];
    [selectView addSubview:quickSel];
    
    UIImageView* iv = [[UIImageView alloc]initWithFrame:CGRectMake(13, selectView.frame.origin.y+selectView.frame.size.height+8, 45, 45)];
    iv.image = [UIImage imageNamed:@"heimashangquanxin_03.png"];
    [newFriendView addSubview:iv];
    
    
    
    UIButton* toNewFriendBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, selectView.frame.size.height, 320, newFriendView.frame.size.height-selectView.frame.size.height)];
    toNewFriendBtn.backgroundColor = [UIColor clearColor];
    [toNewFriendBtn addTarget:self action:@selector(newFriends) forControlEvents:UIControlEventTouchUpInside];
    [newFriendView addSubview:toNewFriendBtn];
    
    
    
    BaseLabel* lab  = [BaseLabel initLabel:@"新的朋友" font:FONT(16) color:RGB(83,83,83) textAlignment:NSTextAlignmentLeft];
    lab.frame = CGRectMake(iv.frame.origin.x+iv.frame.size.width+10, iv.frame.origin.y+13, 100, 20);
    [newFriendView addSubview:lab];
    
    
    myTableView.tableHeaderView = newFriendView;
    
}

- (void)quickFind{
    
    [self getFriendList];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请输入要搜索的人名" message:@"" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"搜索",nil];
    
    [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
    [alert show];
    alert.delegate = self;
    

    
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 1) {
       
        if (_haveNoFriends) {
            UIAlertView* av = [[UIAlertView alloc]initWithTitle:@"您当前没有好友" message:@"" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [av show];
        }
        
        
        UITextField *username=[alertView textFieldAtIndex:0];
        
        if (arrayUser) {
            int i = arrayUser.count;
            NSLog(@"共有%d组",i);
            
            
            for (NSArray* tongSHouPins in arrayUser) {
                
                NSLog(@"总共的数组有%d个：%@",tongSHouPins.count,tongSHouPins);
                
                
                for (NSDictionary* dic in tongSHouPins) {
                   
                    if([username.text isEqualToString:[dic objectForKey:@"username"]]){
                        
                        [arrayUser removeAllObjects];
                        [arrayUser addObject:[NSMutableArray arrayWithObject:dic]];
                        [self checkUnreadMessage];
                        [myTableView reloadData];
                        
                        NSLog(@"查找成功");
                        
                        return;
                        
                    }
                    
                }
                
                //[[BeeUITipsCenter sharedInstance] presentMessageTips:@"用户不存在"];
                
                UIAlertView* av = [[UIAlertView alloc]initWithTitle:@"用户不存在" message:@"" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [av show];
                
                return;
            }
            
            
        }
        
    }

}
- (void)viewWillAppear:(BOOL)animated{

    [self getFriendList];
}


- (void)updateMyFriends{
    [self getFriendList];
    
}



- (void)newFriends{
    
    AcceptNewFriendBoard *board = [[AcceptNewFriendBoard alloc] init];
    
    [[MainBoard sharedInstance].stack pushBoard:board animated:YES];
    
    
    
}

- (void)getFriendList{
    
    
    
    [self POST:[NSString stringWithFormat:@"%@/apiuser/listfriends",kBaseUrl]].PARAM(@"uid",kUserInfo[@"uid"]);
    
    NSLog(@"当前用户的UID：%@",kUserInfo[@"uid"]);
    
   
    
    
}

- (void)handleRequest:(BeeRequest *)request
{
    if(request.failed)
    {
        [[BeeUITipsCenter sharedInstance] dismissTips];
        NETWORK_ERROR
    }
    else if (request.succeed)
    {
        id json = [request.responseString mutableObjectFromJSONString];
        NSLog(@"黑马圈-----------%@",json);
        NSLog(@"info:%@",json[@"info"]) ;
        NSArray* friends = json[@"res"];
        if (friends.count == 0) {
           
            _haveNoFriends = YES;
            
        }
        
        
        
        
        
        
        
        
        switch ([json[@"status"] intValue]) {
                
                
                
                
                
            case 1:
            {
//                [[NSUserDefaults standardUserDefaults] setObject:json[@"res"] forKey:@"userInfo"];
//                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"hasLogin"];
//                MainBoard *board = [MainBoard sharedInstance];
//                [self.stack pushBoard:board animated:YES];
                if (![json[@"res"] isKindOfClass:[NSArray class]]) {
                    
                    
                    return;
                }
                NSArray *array = json[@"res"];
                [arrayUser removeAllObjects];
                for (int i = 0; i < array.count; i++) {
                    BOOL isFind = NO;
                    if (i  == 0) {
                        
//                        NSLog(@"添加新的朋友");
//                        NSMutableDictionary* dicUser = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"thisisnewfriend",@"username" ,nil];
//                        
//                        [arrayUser addObject:[NSMutableArray arrayWithObject:dicUser]];
                        
                    }
                    
                    
                    for (int j = 0; j < arrayUser.count; j++) {
                        if ([arrayUser[j][0][@"ind"] isEqualToString:array[i][@"ind"]]) {
                            [arrayUser[j] addObject:array[i]];
                            isFind = YES;
                        }
                    }
                    if (!isFind) {
                       
                        
                        
                        [arrayUser addObject:[NSMutableArray arrayWithObject:array[i]]];
                    }
                }
                [self checkUnreadMessage];
                [myTableView reloadData];
            }
                break;
                
            default:
                break;
        }
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [arrayUser count];
   
  
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [arrayUser[section] count];
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 20.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70.0;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return arrayUser[section][0][@"ind"];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    FriendCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
    if (nil == cell) {
        cell = [[FriendCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell1"];
        
        [cell initSelf];
    }
    
    
    
    
    cell.dictUser = arrayUser[indexPath.section][indexPath.row];
    cell.backgroundColor = [UIColor clearColor];
    [cell load];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSMutableDictionary *dictUser = arrayUser[indexPath.section][indexPath.row];
    UserDetailBoard *board = [[UserDetailBoard alloc] init];
    board.dictUser = dictUser;
    [[MainBoard sharedInstance].stack pushBoard:board animated:YES];
    
    [self clearUnReadCount:dictUser];
}

- (void)clearUnReadCount:(NSMutableDictionary *)dict{
    NSMutableArray *arrayUnread = [[[NSUserDefaults standardUserDefaults] valueForKey:@"unread"] mutableCopy];
    NSString *strUid = kUserInfo[@"uid"];
    for (int i = 0; i < arrayUnread.count; i++) {
        NSMutableDictionary *dictMessage = arrayUnread[i];
        if ([dictMessage[@"uid"] intValue]==[strUid intValue] && [dictMessage[@"rid"] intValue]==[dict[@"uid"] intValue]) {
            [arrayUnread removeObjectAtIndex:i];
            [[NSUserDefaults standardUserDefaults] setObject:arrayUnread forKey:@"unread"];
            return;
        }
    }
}

@end
